﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using RiskMan.Config;
using RiskMan.DataClass.Models.Quik;
using RiskMan.DataClass.Models.RM;
using RiskMan.Models;
using AvalonDock;
using System.Reflection;
using RiskMan.DataClass.Models;
using RiskMan.Views.Dialogs;


namespace RiskMan.Views.LimitStock
{
    /// <summary>
    /// Логика взаимодействия для LimitStockView.xaml
    /// </summary>
    public partial class LimitStockView : DocumentContent
    {
        private MainWindow mainWindow;
        private DispatcherTimer _dsUpdate;
        private List<PositionModel> positionModel;
        private string _formate;
        VerificationLicense ver = new VerificationLicense();
        public List<String> SeccodeList = new List<String>();

        public LimitStockView()
        {
            mainWindow = RiskMan.MainWindow.StaticRiskMan;
            InitializeComponent();
            this.Title = cfg.MainfunctionLimitstock;

            positionModel = GetCount(mainWindow._dataProvider.EmitentLimiteList);
            positionModel.AddRange(GetCount(mainWindow._dataProvider.FortsPositionsList));
        }

        private void UpdataLines(object sender, EventArgs args)
        {
            if (mainWindow._dataProvider != null)
                for (int i = 0; i < mainWindow._dataProvider.LimitStockList.Count; i++)
                {
                    mainWindow._dataProvider.LimitStockList[i].CurrentPos = mainWindow._dataProvider.GetCurPosition(
                        mainWindow._dataProvider.LimitStockList[i].Seccode,
                        mainWindow._dataProvider.LimitStockList[i].Account,
                        mainWindow._dataProvider.LimitStockList[i].ClientCode);
                }
        }

        private List<string> GetSeccodeList(List<CurrentParamModel> list)
        {
            List<String> result = new List<string>() { cfg.Unknown };

            for (int i = 0; i < list.Count; i++)
                result.Add(list[i].Seccode);

            return result;
        }

        private void LimitStockViewLayout_Loaded(object sender, RoutedEventArgs e)
        {
            this.Update();

            _dsUpdate = new DispatcherTimer();
            _dsUpdate.Interval = cfg.UpdateLimitstockInterval;
            _dsUpdate.Start();
            _dsUpdate.Tick += new EventHandler(LogicMethod);
            _dsUpdate.Tick += new EventHandler(UpdataLines);
        }

        private void Button_AddRow_Click(object sender, RoutedEventArgs e)
        {
            ModuleLimitStockModel nlsItem = new ModuleLimitStockModel();
            newLimitStock nls = new newLimitStock(mainWindow, nlsItem, mainWindow._dataProvider, false);
            nls.ShowDialog();
            ////if (nlsItem.Account != null)
            ////    mainWindow._dataProvider.LimitStockList.Add(nlsItem);
            Update();
            cfg.SetLog("Добавлена строка в таблицe лимитов по бумагам", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        }

        public void Update()
        {
            //dtgdLimitStock.CanUserAddRows = true;

            //mainWindow._dataProvider.LimitStockList = this.GetUpdate(mainWindow._dataProvider.LimitStockList);
            dtgdLimitStock.ItemsSource = mainWindow._dataProvider.LimitStockList;
            //dtgdLimitStock.CanUserAddRows = false;
        }

        private ObservableCollection<ModuleLimitStockModel> GetUpdate(ObservableCollection<ModuleLimitStockModel> observableCollection)
        {
            foreach (var tmp in observableCollection)
            {
                tmp.AccountList = this.GetAccounts();
                tmp.ClientCodeList = this.GetClientCodes();
            }
            return observableCollection;
        }


        private List<string> GetClientCodes()
        {
            List<Trade> trades = new List<Trade>();
            List<String> result = new List<string>();

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                    trades.Add(mainWindow._dataProvider.T2QItems[i].TradeList[j]);

            foreach (var tmp in trades)
            {
                bool tr = false;
                foreach (var tm in result)
                {
                    if (tmp.ClientCode == tm)
                        tr = true;
                }
                if (tr == false)
                    result.Add(tmp.ClientCode);
            }

            return result;
        }

        private List<string> GetAccounts()
        {
            List<Trade> trades = new List<Trade>();
            List<String> result = new List<string>();

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                    trades.Add(mainWindow._dataProvider.T2QItems[i].TradeList[j]);

            foreach (var tmp in trades)
            {
                bool tr = false;
                foreach (var tm in result)
                {
                    if (tmp.Account == tm)
                        tr = true;
                }
                if (tr == false)
                    result.Add(tmp.Account);
            }

            return result;
        }

        /// <summary>
        /// Отмечаем строки 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LimitStockList.Count; i++)
            {
                mainWindow._dataProvider.LimitStockList[i].Check = (sender as CheckBox).IsChecked.Value;
            }
            dtgdLimitStock.ItemsSource = mainWindow._dataProvider.LimitStockList;
        }



        private void dtgdLimitStock_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ObservableCollection<Limits> tmpCollForEdit = new ObservableCollection<Limits>();
            string tmpClientcode = null;
            if ((sender as DataGrid).SelectedItems.Count == 1)
            {
                foreach (var item in mainWindow._dataProvider.LimitStockList)
                    if (item.Equals(((DataGrid)sender).SelectedItem))
                    {
                        tmpClientcode = item.ClientCode;
                        break;
                    }

                foreach (var item in mainWindow._dataProvider.LimitStockList)
                    if (item.ClientCode==tmpClientcode)
                    {
                        tmpCollForEdit.Add(new Limits() {instrument=item.Seccode, limit=item.LimitStock.ToString(), regim=item.Regim });
                    }

                newLimitStock nls = new newLimitStock(tmpCollForEdit, mainWindow, ((DataGrid)sender).SelectedItem as ModuleLimitStockModel, mainWindow._dataProvider, true);
                nls.ShowDialog();


                Update();
                //cfg.SetLog("Отредактирована строка в таблице стопов", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
            }
        }

        #region Копировать строку в конец

        private void dtgdLimitStock_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            //if ((sender as System.Windows.Controls.DataGrid).SelectedItems.Count == 1)
            //{
            //    int index = (sender as System.Windows.Controls.DataGrid).SelectedIndex + 1;
            //    DataGrid_SL.UnselectAll();
            //    if (new DialogYesNo("Вы действительно хотите скопировать строку " + index + "?", "Внимаение").Result == MessageBoxResult.Yes)
            //    {
            //        var tmp = (StopListModel)cfg.DeepClone(mainWindow._dataProvider.StopList[index - 1 < 0 ? 0 : index - 1]);
            //        if (tmp.IsStart == false)
            //            mainWindow._dataProvider.StopList.Add(tmp);
            //        else
            //            new DialogOkCancel("Для продолжения копирования нужно остановить копируемю строку", "Ошибка");
            //    }
            //}
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            ObservableCollection<Limits> tmpCollForEdit = new ObservableCollection<Limits>();
            string tmpClientcode = null;
            if (dtgdLimitStock.SelectedItems.Count == 1)
            {
                foreach (var item in mainWindow._dataProvider.LimitStockList)
                    if (item.Equals(dtgdLimitStock.SelectedItem))
                    {
                        tmpClientcode = item.ClientCode;
                        break;
                    }

                foreach (var item in mainWindow._dataProvider.LimitStockList)
                    if (item.ClientCode == tmpClientcode)
                    {
                        tmpCollForEdit.Add(new Limits() { instrument = item.Seccode, limit = item.LimitStock.ToString() });
                    }

                newLimitStock nls = new newLimitStock(tmpCollForEdit, mainWindow, dtgdLimitStock.SelectedItem as ModuleLimitStockModel, mainWindow._dataProvider, false);
                nls.ShowDialog();

                if (nls.DialogResult == true)
                { 
                
                }

                //update();
                //cfg.SetLog("Отредактирована строка в таблице стопов", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
            }
        }

        #endregion

        /// <summary>
        /// Удаление строк лимитов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                for (int i = 0; i < mainWindow._dataProvider.LimitStockList.Count; i++)
                {
                    if (mainWindow._dataProvider.LimitStockList[i].Check == true)
                    {
                        mainWindow._dataProvider.LimitStockList.RemoveAt(i);
                        i--;
                    }
                }
            }
            catch (Exception ex)
            {

            }

            Update();
        }

        /// <summary>
        /// Остановка
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            //vers.RemoveAccountLicense(mainWindow, "SL");

            try
            {
                for (int i = 0; i < mainWindow._dataProvider.LimitStockList.Count; i++)
                {
                    if (mainWindow._dataProvider.LimitStockList[i].Check == true)
                    {
                        mainWindow._dataProvider.LimitStockList[i].IsRun = false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            Update();
        }

        /// <summary>
        /// Запуск
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            //    if (vers.CountAccountLicense(mainWindow, "SL") == false)
            //    {
            //        new DialogOkCancel("Количество запускаемых счетов больше, чем приобретено лицензий. Одна лицензия - один счет ММВБ и один счет ФОРТС", "Предупреждение");
            //        return;
            //    }
            //}
            //catch
            //{

            //}

            try
            {
                bool tr = false;
                var list = mainWindow._dataProvider.LimitStockList.Where(a => a.Check == true).ToList();
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].IsRun == false)
                    {
                        var tmp = mainWindow._dataProvider.LimitStockList.Where(a => a.Seccode == list[i].Seccode &&
                                                  a.Account == list[i].Account &&
                                                  a.ClientCode == list[i].ClientCode &&
                                                  a.IsRun == true).ToList();
                        if (tmp.Count != 0)
                            tr = true;
                        else list[i].IsRun = true;
                    }
                }

                if (tr == true)
                    new DialogMessage("Несколько однаковых по типу, счету и бумаге стопов не могут быть запущены обновременно ", "Внимание!");
            }
            catch (Exception ex)
            {

            }
            dtgdLimitStock.ItemsSource = mainWindow._dataProvider.LimitStockList;
        }

        /// <summary>
        /// Работа с чекбоками в датагриде
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtgdLimitStock_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as DataGrid).SelectedItems.Count == 1)
            {
                bool tr = mainWindow._dataProvider.LimitStockList[(sender as DataGrid).SelectedIndex].Check == true ? false : true;
                mainWindow._dataProvider.LimitStockList[(sender as DataGrid).SelectedIndex].Check = tr;
            }
            dtgdLimitStock.ItemsSource = mainWindow._dataProvider.LimitStockList;
        }

        private void dtgdLimitStock_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }
}
